<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-10-13
 * Time: 17:59
 */

namespace app\api\model\mp\v1;


use think\facade\Log;
use think\facade\Request;

use WxThirdPartyPlatform\WXBizMsgCrypt;
use WxThirdPartyPlatform\XMLParse;

class WXMPNotifyEvent
{
    private $app_id = '';
    private $app_secret = '';
    private $receive_msg_token = '';
    private $receive_msg_ende_key = '';
    private $pc = null;

    public function __construct()
    {
        $this->app_id = get_wx_config('mp_app_id');
        $this->app_secret = get_wx_config('mp_app_secret');
        $this->receive_msg_token = get_wx_config('mp_receive_msg_verify_token');
        $this->receive_msg_ende_key = get_wx_config('mp_receive_msg_ende_key');

        $this->pc = new WXBizMsgCrypt($this->receive_msg_token, $this->receive_msg_ende_key, $this->app_id);
    }

    /**
     * 验证接收消息推送的服务器是否有效
     * @return bool
     */
    public function VerifyMessagePushSignature()
    {
        $signature = Request::get('signature','');
        $timestamp = Request::get('timestamp','');
        $nonce = Request::get('nonce','');

//        Log::record($signature,'error');
//        Log::record($nonce,'error');
//        Log::record($timestamp,'error');
//        Log::record($this->receive_msg_token,'error');
//        Log::record(Request::get('echostr',''),'error');

        $array = array($this->receive_msg_token, $timestamp, $nonce);
        sort($array, SORT_STRING);
        $str = implode($array);
        $str = sha1($str);

        if ($str == $signature) {
//            Log::record('true','error');
            return true;
        } else {
            return false;
        }
    }

    /**
     * 处理接收到消息推送信息
     */
    public function HandleMessagePushEvent()
    {
        // 存放解密后的信息
        $msg = '';

        // 获取时间戳
        $time_stamp = Request::get('timestamp', '');
        // 获取随机数
        $nonce = Request::get('nonce', '');
        // 获取加密类型
        $encrypt_type = Request::get('encrypt_type','aes');
        // 获取消息体签名
        $msg_signature = Request::get('msg_signature','');

        // 获取postdata中的xml数据
        $encrypt_msg = file_get_contents('php://input');

        // 对收到的开放平台的信息进行解密
        $err_code = $this->pc->decryptMsg($msg_signature, $time_stamp, $nonce, $encrypt_msg, $msg);

        Log::record($time_stamp,'error');
        Log::record($nonce,'error');
        Log::record($msg_signature,'error');
        Log::record($encrypt_msg,'error');

        if ($err_code == 0) {
            // 解密成功
            // 将解密成功的数据转换为数组
            $encrypt_data = XMLParse::xml2arr($msg);

            Log::record(json_encode($encrypt_data, JSON_UNESCAPED_UNICODE), 'error');

            // 判断接收的信息是什么类型
//            $info_type = $encrypt_data['InfoType'];
//            switch($info_type) {
//                case 'component_verify_ticket':
//                    // 第三方平台验证票据
//                    if(!isset($encrypt_data['ComponentVerifyTicket'])) {
//                        throw new \Exception('获取第三方平台验证票据，Ticket不存在');
//                    }
//                    $this->saveToCache($encrypt_data['ComponentVerifyTicket']);
////                    Log::record('ComponentVerifyTicket:'.$encrypt_data['ComponentVerifyTicket'],'error');
//                    break;
//                case 'unauthorized':
//                    // 取消授权
//                    break;
//                case 'updateauthorized':
//                    // 更新授权
//                    break;
//                case 'authorized':
//                    // 授权成功
//                    break;
//                default:
//                    throw new \Exception('无法判断第三方平台接收到数据类型，类型为：'.$info_type);
//            }
        } else {
            // 解密失败
            throw new \Exception('解密微信小程序推送的消息事件失败，错误代码为：'.$err_code);
        }
    }
}